package com.shenhaofeng.app.loader.list.util;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;


/**
 * Created by Administrator on 2016/7/22.
 */
public class ScrollToBottomHelper {


    private RecyclerView mRecyclerView;

    private boolean eventable = false;

    private Callback mCallback;


    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            boolean enable = false;
            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                int lastPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                if (lastPosition == recyclerView.getAdapter().getItemCount() - 1) {
                    enable = true;
                }
            }
            if (mCallback != null && enable && eventable) {
                eventable = false;
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mCallback.onScrollToBottom();
                    }
                },30);
            }
        }
    };





    /**
     * 是否能够触发加载事件
     *
     * @param enable
     */
    public void setEventEnable(boolean enable) {
        eventable = enable;
    }





    public void setup(RecyclerView recyclerView, Callback callback) {
        this.mRecyclerView = recyclerView;
        this.mCallback = callback;
        mRecyclerView.addOnScrollListener(mOnScrollListener);
    }





    public void invalid() {
        mRecyclerView.removeOnScrollListener(mOnScrollListener);
        mRecyclerView = null;
    }





    public interface Callback {
        void onScrollToBottom();
    }


}
